package com.guigu.www.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

@Configuration
@MapperScan("com.guigu.www.mapper")
@PropertySource("classpath:config.properties")
public class ApplicationContextConfig {

    @Value("${jdbc.connectionURL}")
    private String url;
    @Value("${jdbc.userId}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    //初始化连接池
    @Bean
    public DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    //实例SqlSession对象，使用mybatis-plus操作数据库
    @Bean
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean(DruidDataSource dataSource){
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        Resource resource = new ClassPathResource("mybatisConfig.xml");
        bean.setDataSource(dataSource);
        bean.setConfigLocation(resource);
        return bean;
    }
}
